package com.example.datasync.run;

import com.example.datasync.service.OrgService;
import com.example.datasync.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @Class 项目启动后运行此方法:CommandLineRunner实现
 */
@Component
public class FtpInitRunner implements CommandLineRunner {

    private static final Logger LOG = LoggerFactory.getLogger(FtpInitRunner.class);

    final
    UserService userService;

    final
    OrgService orgService;

    public FtpInitRunner(UserService userService, OrgService orgService) {
        this.userService = userService;
        this.orgService = orgService;
    }

    /**
     * 测试方法.
     *
     * @param var1
     * @throws Exception
     */
    @Override
    public void run(String... var1) throws Exception {
        LOG.info("--执行数据同步-开始:");

        // 获取所有个人版组织
        List<Map> orgList = orgService.selectOrg();
        LOG.info("获取所有个人版组织条数:{}", orgList.size());

        Map<String, String> orgMap = new HashMap<>();
        for (Map map : orgList) {
            String userId = String.valueOf(map.get("user_id"));
            String orgId = String.valueOf(map.get("id"));
            if (orgMap.containsKey(userId)) {
                LOG.info("OrgMap 用户对照存在重复个人版组织，用户id：{}，组织id:old {}，new {}", userId, orgMap.get(userId), orgId);
            }
            orgMap.put(userId, orgId);
        }
        LOG.info("OrgMap 用户对照条数:{}", orgMap.size());

        for (String userId : orgMap.keySet()) {
            // 获取用户信息
            List<Map> record = userService.selectUser(userId);
            if (!CollectionUtils.isEmpty(record)) {
                // 用户信息组织id
                String orgId = String.valueOf(record.get(0).get("org_id"));

                if (!orgId.equals(orgMap.get(userId))) {
                    userService.updateOrgId(orgMap.get(userId), userId);
                    LOG.info("用户id:{},原数据库存储orgId为：{},此次修改orgId为：{}", userId, orgId, orgMap.get(userId));
                }
            }
        }

        LOG.info("--执行数据同步-结束.");
    }

}